package com.xiaohong.oauth.config;

import com.xiaohong.user.feign.ChatUserFeign;
import com.xiaohong.user.pojo.User;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import util.UserJwt;

import java.util.List;

/*****
 * 自定义授权认证类
 */
@Service
@EnableFeignClients(basePackages = {"com.xiaohong.user.feign"})
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    private ChatUserFeign chatUserFeign;

    /****
     * 自定义授权认证
     * @param identity 用户认证信息
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String identity) throws UsernameNotFoundException {
        //=================客户端信息认证 start
        // 这里会执行两遍，第一遍identity是application里设置的xiaohong，第二遍是用户输入的认证信息
        //取出身份，如果身份为空说明没有认证
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
        if(authentication==null){
            //查询数据库
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(identity);
            if(clientDetails!=null){
                //秘钥
                String clientSecret = clientDetails.getClientSecret();
                //静态方式
                //return new User(username,new BCryptPasswordEncoder().encode(clientSecret), AuthorityUtils.commaSeparatedStringToAuthorityList(""));
                //数据库查找方式  最后一个是权限
//                return new org.springframework.security.core.userdetails.User(identity,  //客户端id
//                        clientSecret,   //客户端密钥
//                        AuthorityUtils.commaSeparatedStringToAuthorityList(""));
                return new org.springframework.security.core.userdetails.User(identity,  //客户端id
                        clientSecret,   //客户端密钥
                        clientDetails.getAuthorities());
            }
        }
        //=================客户端信息认证 end
        //=================用户账号密码信息认证 start
        if (StringUtils.isEmpty(identity)) {
            return null;
        }


        //从数据库获取用户信息
        User user = new User();
        user.setUsername(Long.valueOf(identity));
        Result<List<User>> userResult = chatUserFeign.findList(user);

        if (userResult == null || userResult.getData().size() == 0){
            return null;
        }

        //根据用户名查询用户信息
        User userInfo = userResult.getData().get(0);
        String pwd = userInfo.getPassword(); //new BCryptPasswordEncoder().encode("szitheima");
        Long id = userInfo.getId();
        //创建User对象
        String[] permissions = new String[0];
        if (!StringUtils.isEmpty(userInfo.getAuthorities())){
            permissions = userInfo.getAuthorities().split(",");
        }
        UserJwt userDetails = new UserJwt(identity,pwd,
                userInfo.getEnabled() == 0,
                userInfo.getAccountNonExpired() == 0,
                userInfo.getCredentialsNonExpired() == 0,
                userInfo.getAccountNonLocked() == 0,
                AuthorityUtils.createAuthorityList(permissions),
                user.getNickName());
        //=================用户账号密码信息认证 end
        System.out.println("user用户："+userDetails);
        return userDetails;
    }
}
